// pages/bindphone/bindphone.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    uqid:"",
    txt: "获取验证码",
    time: 60,
    phone:"",
    code:""
  },

  toprivacy: function() {
    wx.navigateTo({
      url: '/pages/privacy/privacy',
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var uqid=wx.getStorageSync("uqid");
    this.setData({
      uqid: uqid
    })
  },

  checkPhone:function () {
    var phone = this.data.phone
    if (!(/^1[3456789]\d{9}$/.test(phone))) {
      return false;
    }else{
      return true;
    }
  },
  getphonecode: function() {
    if (this.data.time == 60) {
      if(this.checkPhone()){
        ajax('/api/user/sms', {
          data: {
            phone:this.data.phone
          },
          header: {
            'Accept': 'application/json', // 默认值
          },
          method: 'get'
        }, res => {
          console.log(res)

        })
      }else{
        wx.showToast({
          title: '请输入正确手机号',
          icon: 'none',
          duration: 2000
        })
        return false;
      }

      var that = this
      var timer = setInterval(function() {
        that.data.time--
          that.setData({
            txt: that.data.time + "秒后重新获取"
          })
        if (that.data.time == 0) {
          that.setData({
            txt: "获取验证码",
            time: 60
          })
          clearInterval(timer)
        }
      }, 1000)
    } else {
      return false
    }

  },
  addphone:function(){
    ajax('/api/user/phone_add', {
      data: {
        phone: this.data.phone,
        uqid:this.data.uqid,
        code:this.data.code,
      },
      header: {
        'Accept': 'application/json', // 默认值
      },
      method: 'post'
    }, res => {
      console.log(res)
      if (res.error==0){
        wx.showToast({
          title: "绑定成功",
          icon: 'none',
          duration: 2000
        })
        wx.setStorageSync("tel", this.data.phone)

        setTimeout(function(){
          // 第一次
          wx.navigateBack({
            delta: 1
          })
        },1000)

      } else if (res.error == 4008){
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }

    })
  },

  getphone: function(e) {
    this.setData({
      phone: e.detail.value
    });
  },
  getcode: function(e) {
    this.setData({
      code: e.detail.value
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})